import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Button, ConfigProvider, Icon, Select, message } from 'antd';
import FileUpload from '@/components/Custom/FileUpload/FileUpload';
import { modalTypes } from './modalTypes';
import ScoreTable from './ScoreTable';
import ReRateInfo from './ReRateInfo';
import { getRescoreApplyInfo } from '../../services/score';
import { LaunchRatingFormItems, MoveToNoRateFormItems } from './ScoreOpt';

import styles from './index.less';

const { TextArea } = Input;

const ScoreModal = ({
    form,
    type,
    visible,
    setVisible,
    onOk,
    onCancel,
    data = {},
    userConfig,
    employeeList,
    isDetail = false,
    modalTableData = []
}) => {
    const { getFieldDecorator, validateFields } = form;
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [count, setCount] = useState(500);
    const [disableUpload, setDisableUpload] = useState(false);
    const [reScoreApplyInfo, setReScoreApplyInfo] = useState({});
    // const [reRateEmployeeList, setReRateEmployeeList] = useState([]);
    const handleOk = () => {
        validateFields((err, values) => {
            if (err) {
                return;
            }
            if (onOk) onOk(values, setConfirmLoading, type, data);
        });
    };

    const handleCancel = () => {
        if (onCancel) onCancel();
        setVisible(false);
    };

    useEffect(
        () => () => {
            setCount(500);
            setConfirmLoading(false);
            setDisableUpload(false);
            form.resetFields();
        },
        [visible]
    );

    const formItemLayout = {
        style: { paddingLeft: 12, paddingRight: 12 },
        labelCol: { span: 4 },
        wrapperCol: { span: 20 }
    };

    const onTextAreaChange = e => {
        const val = 500 - e.currentTarget.value.length;
        if (val >= 0) {
            setCount(val);
        }
    };

    const onFileChange = fileData => {
        if (fileData.allFileList.length >= 5) {
            setDisableUpload(true);
        } else {
            setDisableUpload(false);
        }
    };

    const ratingTableItem = (
        <Form.Item wrapperCol={{ span: 24 }}>
            <ScoreTable form={form} data={data} isDetail={isDetail} modalTableData={modalTableData} />
        </Form.Item>
    );

    const assessmentContentItem = (
        label = '评价内容',
        placeholder = '请输入评价内容',
        isRequired = false,
        field = 'content'
    ) => {
        const helpText = isDetailText => {
            if (!isDetailText) {
                return (
                    <span>
                        还可以输入
                        <span style={{ color: 'red' }}>{count}</span>
                        个字
                    </span>
                );
            }
            return '';
        };
        return (
            <Form.Item
                label={label}
                help={form.getFieldError(field) ? undefined : helpText(isDetail)}
                required={isRequired}
            >
                {!isDetail &&
                    getFieldDecorator(field, {
                        initialValue: '',
                        rules: [
                            { required: isRequired, message: `请输入${label}` },
                            {
                                pattern: /^[^\s]+(\s+[^\s]+)*/,
                                message: '此处不能以空格开头'
                            }
                        ]
                    })(<TextArea rows={5} placeholder={placeholder} maxLength={500} onChange={onTextAreaChange} />)}
                {isDetail && <span>{data[field]}</span>}
            </Form.Item>
        );
    };

    const getDetailFile = taskScoreFile => {
        if (taskScoreFile && taskScoreFile.length > 0) {
            return taskScoreFile.map(item => (
                <div className={styles.detailAttachFile}>
                    <div>
                        <a href={item.url}>{item.originName}</a>
                    </div>
                    <div>
                        <a href={item.url}>
                            <Icon type="download"></Icon>
                        </a>
                    </div>
                </div>
            ));
        }
        return '无';
    };

    const attachFileItem = (dataField = 'taskScoreFile', categoryCode = 'taskScoreFile') => (
        <Form.Item label="附件">
            {!isDetail && (
                <>
                    <span className={styles.attachRemark}>
                        （支持非运行文件格式，每个文件大小不超过50M，最多上传5个附件）
                    </span>
                    {getFieldDecorator(
                        'files',
                        {}
                    )(
                        <FileUpload
                            onChange={onFileChange}
                            categoryCode={categoryCode}
                            checkFileSize={50}
                            checkFileSizeMsg="文件大小不能超过50MB！"
                            checkFileType="TXT,DOC,DOCX,XLS,XLSX,PPT,PPTX,PDF,EDC,SSP,DWG,EDCS,
                            BMP,JPG,PNG,TIF,GIF,PCX,TGA,EXIF,FPX,SVG,PSD,CDR,PCD,DXF,UFO,EPS,AI,
                            RAW,WMF,WEBP,Xmind,ZIP,rar,zip,CAB,ARJ,LZH,TAR,GZ,ACE,UUE,BZ2,JAR,ISO,rp"
                            checkFileTypeMsg="附件格式不合规，请确认！"
                        >
                            <Button style={{ padding: 0 }} type="link" disabled={disableUpload}>
                                添加附件
                            </Button>
                        </FileUpload>
                    )}
                </>
            )}
            {isDetail && getDetailFile(data[dataField])}
        </Form.Item>
    );

    const initialRatingFormItems = () => (
        <>
            {ratingTableItem}
            {assessmentContentItem()}
            {attachFileItem()}
        </>
    );

    const giveUpRateItems = () => (
        <>
            {assessmentContentItem('原因', '请输入原因', true)}
            {attachFileItem()}
        </>
    );

    const reRatingFormItems = () => (
        <>
            {!isDetail && <div className={styles.reRateTitle}>当前任务已申请重评，请重新评分！</div>}
            {ratingTableItem}
            {assessmentContentItem()}
            {attachFileItem()}
            <ReRateInfo {...reScoreApplyInfo} />
        </>
    );

    const getNoticeItem = () => {
        if (!!data.launchEmployeeName && data.executorName !== data.launchEmployeeName) {
            return (
                <Form.Item label="温馨提示">
                    确定后，需由发起人【{data.launchEmployeeName}】审核通过后方可生效
                </Form.Item>
            );
        }
        if (data.auditEmployeeName) {
            return (
                <Form.Item label="温馨提示">确定后，需由审核人【{data.auditEmployeeName}】审核通过后方可生效</Form.Item>
            );
        }
        return '';
    };

    const reRateApplyFormItems = () => (
        <div className={styles.reRateApply}>
            {!isDetail && data?.executorName && getNoticeItem()}
            <Form.Item label={isDetail ? '选择重评人员' : '请选择重评人员'} required>
                {!isDetail &&
                    form.getFieldDecorator('employeeList', {
                        rules: [{ required: true, message: '请选择重评人员' }],
                        initialValue: data?.employeeList?.map(item => item.employeeName)
                    })(
                        <Select mode="multiple" placeholder="请选择重评人员" disabled={isDetail}>
                            {data?.reRateEmployeeList?.map(item => (
                                <Select.Option value={item.value}>{item.label}</Select.Option>
                            ))}
                        </Select>
                    )}
                {isDetail && data?.employeeList?.map(item => item.employeeName).join('；')}
            </Form.Item>
            {assessmentContentItem('原因', '请输入原因', true, 'operateReason')}
            {attachFileItem('taskReScoreFile', 'taskReScoreFile')}
        </div>
    );

    React.useEffect(() => {
        if (visible && (type === modalTypes.RE_RATE.key || type === modalTypes.RE_SCORE_DETAIL.key)) {
            // 获取重评申请和审核的信息
            const getDetailData = async () => {
                if (!data.taskScoreDetailId) {
                    return message.warning('未获取到taskScoreDetailId');
                }
                const { code, data: applyInfo, msg } = await getRescoreApplyInfo(data);
                if (code === 10000) {
                    setReScoreApplyInfo(applyInfo);
                } else {
                    message.error(msg);
                }
                return null;
            };
            getDetailData();
        }
    }, [visible]);

    const getFormItems = () => {
        if (!type) return '';
        switch (type) {
            case modalTypes.INITIAL_RATE.key: // 评分
            case modalTypes.SCORE_DETAIL.key:
            case modalTypes.AUTO_SCORE_DETAIL.key:
                return initialRatingFormItems();
            case modalTypes.RE_RATE.key: // 重评
            case modalTypes.RE_RATE_DETAIL.key:
            case modalTypes.RE_SCORE_DETAIL.key: // 评分记录里面的重评结果详情
                return reRatingFormItems();
            case modalTypes.RE_RATE_APPLY.key: // 重评申请
            case modalTypes.RE_RATE_APPLY_DETAIL.key:
                return reRateApplyFormItems();
            case modalTypes.GIVE_UP_RATE.key: // 放弃评分
            case modalTypes.GIVE_UP_RATE_DETAIL.key:
                return giveUpRateItems();
            case modalTypes.LAUNCH_RATE.key: // 发起评分
            case modalTypes.LAUNCH_RATE_DETAIL.key:
            case modalTypes.BATCH_START.key:
                return (
                    <LaunchRatingFormItems
                        form={form}
                        data={data}
                        isDetail={isDetail}
                        userConfig={userConfig}
                        employeeList={employeeList}
                    />
                );
            case modalTypes.BATCH_NO_SCORE.key: // 批量无需评分
            case modalTypes.MOVE_TO_NO_RATE.key: // 移入无需评分
                return MoveToNoRateFormItems({ form, data });
            case modalTypes.MOVE_TO_WAIT.key: // 移回待发起
            case modalTypes.BATCH_MOVE.key: // 批量移回待发起
                return MoveToNoRateFormItems({ form, data, confirmText: '确定将以下任务移回待发起？' });
            default:
                return '';
        }
    };

    return (
        <Modal
            title={(type && modalTypes[type].title) || ''}
            width={800}
            visible={visible}
            onCancel={handleCancel}
            maskClosable={false}
            confirmLoading={confirmLoading}
            className={styles.scoreModal}
            footer={null}
            destroyOnClose
        >
            <div className={styles.scoreFormWrap}>
                <ConfigProvider getPopupContainer={node => node.parentNode}>
                    <Form {...formItemLayout}>{getFormItems()}</Form>
                </ConfigProvider>
                <div className={styles.bottomButton}>
                    {!isDetail && (
                        <>
                            <Button onClick={handleCancel}>取消</Button>
                            <Button onClick={handleOk} type="primary" loading={confirmLoading}>
                                确定
                            </Button>
                        </>
                    )}
                    {isDetail && (
                        <Button onClick={handleCancel} type="primary">
                            确定{' '}
                        </Button>
                    )}
                </div>
            </div>
        </Modal>
    );
};

export default Form.create()(ScoreModal);
